<template>
  <!-- 列表 -->
  <ContentWrap>
    <el-button
      type="primary"
      plain
      @click="openForm('create')"
      v-hasPermi="['farm:pc:create']"
    >
      <Icon icon="ep:plus" class="mr-5px" /> 新增
    </el-button>

    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="农舍" align="center" prop="houseName" />
       <el-table-column label="鸡舍类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag  :type="DICT_TYPE.FARM_FARMHOUSE_TYPE" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="记录先前数据" align="center" prop="preId" /> -->
      <el-table-column label="进舍总数" align="center" prop="inNum" />
      <el-table-column label="剩余数量" align="center" prop="num" />
      <el-table-column v-if="typeName ==='蛋鸡舍'" label="预计淘汰日期" align="center" prop="expectedEliminateTime" :formatter="dateFormatter2" :show-overflow-tooltip="true" />
      <el-table-column v-if="typeName ==='蛋鸡舍'" label="淘汰日期" align="center" prop="eliminateTime" :formatter="dateFormatter2"  />
      <el-table-column v-if="typeName ==='蛋鸡舍'" label="淘汰完成日期" align="center"  prop="eliminateFinishTime"  :formatter="dateFormatter2"/>
      <el-table-column label="入舍日期" align="center" prop="inFarmhouseTime" :formatter="dateFormatter2"/>
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" fixed="right" align="center" width="180">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['farm:pc:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['farm:pc:delete']"
          >
            删除
          </el-button>

          <el-button v-if="typeName === '蛋鸡舍'" link type="warning" @click="openEliminationDialog(scope.row)">淘汰</el-button>

          <el-dropdown v-else trigger="click" @command="(command)=>handleDropdownCommand(command,scope.row)"> 
            <el-button link type="primary" icon="more" size="small" style="margin-top:5px">
              更多
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
            </el-button>          
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-for="houseType in availableHouseTypes" :key="houseType.value" :command="houseType.value">
                  {{'入'+houseType.label}}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
      
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
    <!-- 表单弹窗：添加/修改 -->
    <InFarmhouseForm ref="formRef" @success="getList" />


    <!-- 入舍类型弹窗 -->
    <el-dialog :title="title" v-model="moreOpen" width="660px" append-to-body>
      <el-form ref="layerRef" :rules="InFormRules" :model="selectedRow" label-width="90px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="农舍" prop="houseNameType">
              <el-select v-model="selectedRow.houseNameType" placeholder="请选择农舍" >
                <el-option
                  v-for="item in InHouseList"
                  :key="item.id"
                  :label="item.houseName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="未入舍数"   prop="num">
              <el-input v-model="selectedRow.num" disabled placeholder="" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="入舍数量" prop="inHouseNum">
              <el-input-number v-model="selectedRow.inHouseNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="'入舍日期'" prop="inTime">
              <el-date-picker v-model="selectedRow.inTime" value-format="YYYY-MM-DD" type="date" placeholder="选择日期"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input v-model="selectedRow.description" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="layerSubmitForm(selectedRow)">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 蛋鸡淘汰弹窗 -->
    <el-dialog :title="title" v-model="eliminateOpen" width="660px" append-to-body>
      <el-form ref="eliminateRef" :rules="outEggRules" :model="outHouseForm" label-width="90px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="蛋鸡舍" prop="houseName">
              <el-input v-model="outHouseForm.houseName" placeholder="" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计淘汰" prop="expectedEliminateTime">
              <!-- <el-input v-model="outHouseForm.expectedEliminateTime" placeholder="" disabled  /> -->
              <el-date-picker 
                v-model="outHouseForm.expectedEliminateTime" 
                disabled
                type="date" 
                value-format="x" 
                placeholder="选择日期"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="'实际淘汰'" prop="eliminateTime">
              <el-date-picker 
                v-model="outHouseForm.eliminateTime" 

                type="date" 
                value-format="x" 
                placeholder="选择日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="'淘汰完成'" prop="eliminateFinishTime">
              <el-date-picker v-model="outHouseForm.eliminateFinishTime"   value-format="x"  type="date"  placeholder="选择日期"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="outHouseForm.description" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="eliminateSubmitForm">确 定</el-button>
          <el-button @click="Outcancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import { getStrDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { PcApi } from '@/api/farm/pc'
import InFarmhouseForm from './InFarmhouseForm.vue'
import { dateFormatter2 } from '@/utils/formatTime'
import { string } from 'vue-types'
import { defineExpose } from 'vue'
import { ArrowDown } from '@element-plus/icons-vue'
import{debounce} from 'lodash'
import { get } from 'http'
import { error } from 'console'
import { all } from 'axios'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const title =ref<string>('')//更多弹窗标题
// 入舍弹窗
const moreOpen = ref(false)
const selectedRow = reactive({
  id:undefined,
  houseNameType:'',//入舍类型
  num:undefined,//未入舍数
  inHouseNum:undefined,//入舍数量
  inTime:undefined,//入舍日期
  description:'',//备注
  preId:undefined,
  type: undefined as number | undefined // 确保 type 可以是 number 或 undefined
})
/** 添加/修改操作 */
const formRef = ref()

// 蛋鸡
const outEggForm = ref({})

const InHouseList = ref([])//入鸡舍类型数组

// 淘汰弹窗
const eliminateOpen =ref(false)
// 淘汰表单
const outForm = reactive({
  id:undefined,
  houseName:'',
  expectedEliminateTime:undefined,//预计淘汰
  eliminateTime:undefined,//实际淘汰
  eliminateFinishTime:undefined,//淘汰完成
  description:''//描述
})



interface OutHouseFormTs {
  id: number | undefined;
  houseName: string;
  expectedEliminateTime: number | undefined;
  eliminateTime: number | undefined;
  eliminateFinishTime: number | undefined;
  description: string;
}
const outHouseForm =reactive<OutHouseFormTs>({
  id: undefined,
  houseName: '',
  expectedEliminateTime: undefined,
  eliminateTime: undefined,
  eliminateFinishTime: undefined,
  description: '',
})

// 类型必填
const InFormRules = reactive({
  houseNameType: [{ required: true, message: '农舍不能为空', trigger: 'blur' }],
  inHouseNum: [{ required: true, message: '入舍数量不能为空', trigger: 'blur' }],
  // inTime: [{ required: true, message: '入舍日期不能为空', trigger: 'change' }],
})

// 蛋鸡淘汰必填
const outEggRules =reactive({
  eliminateTime: [{ required: true, message: '实际淘汰日期不能为空', trigger: 'blur' }],
  eliminateFinishTime: [{ required: true, message: '淘汰完成日期不能为空', trigger: 'blur' }],
})

// 传递参数以及类型限制
const props =defineProps({
  pcId:{
    type:Number,
    required:false,
  },
  type:{
    type:String,
    required:true,
  },
  typeName:{
    type:String,
    required:true
  },
  activeHouse:{
    type:String,
    required:false
  }
})
// console.log(props.activeHouse,'activeHouse');

// console.log(props.pcId,'props.pcId');
// console.log(props.type,'props.type');
// console.log(props.typeName,'props.typeName');
const loading = ref(false) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  pcId: props.pcId,
  // 改
  type:props.type
})
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PcApi.getInFarmhousePage(queryParams)
    // console.log(data,'data');
    list.value = data.list.map(item =>{
      const expectedEliminateTime  = item.inTime +500*24*60*60*1000 //换算时间
      return{
        ...item,//将所有的属性赋值到新的属性上
        expectedEliminateTime:expectedEliminateTime
      }
    })
    total.value = data.total

  } finally {
    loading.value = false
  }
}


/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch( () => props.pcId, async(val: number) => {
   if (!val) {
    return 
  }
  queryParams.pcId = val
  handleQuery()
},
{ immediate: true, deep: true }
)

// 监听props.activeHouse变化
watch(()=>props.activeHouse,(newValue)=>{
  // 判断pcId存在并且activeHouse是否和props.type相同在调用刷新getList()
    if(props.pcId && newValue === props.type){
      getList()
    }else{
      return 
    }
},{immediate:true})


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}


const openForm = (type: string, id?: number) => {
  if (!props.pcId) {
    message.error('请选择一个批次')
    return
  }  
  formRef.value.open(type, id, props.pcId,props.type)

}



/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除

    await PcApi.deleteInFarmhouse(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

// 计算激活鸡舍过滤,只显示另外两个入舍按钮
const availableHouseTypes = computed(()=>{
  const allHouseType = getStrDictOptions(DICT_TYPE.FARM_FARMHOUSE_TYPE)
  if(props.type === '0'){
    return allHouseType.filter(type => type.value === '1' || type.value === '2'); // 只显示育成和蛋鸡
  }else if(props.type === '1'){
    return allHouseType.filter(type => type.value ==='2');
  }else if(props.type === '2'){
    return []
  }
   return []; // 默认情况下不显示任何按钮
})

// 更多操作
const handleDropdownCommand =async (command:any,row:any)=>{
  console.log(row,'row');
  Object.assign(selectedRow,{...row})
  moreOpen.value =true;//打开更多操作
  
  // console.log(selectedRow.value,'selectedRow.value');
  await InHouseType(command)
  switch(command){
    case '0':
      title.value ="入育雏舍";
      selectedRow.type = 0
      break;
    case '1':
      title.value ="入育成舍";
      selectedRow.type = 1
      break;
    case '2':
      title.value ="入蛋鸡舍";
      selectedRow.type =2
      break;
    default:
      title.value =''
      selectedRow.type = undefined
  }

}
// 入舍确定操作
const layerSubmitForm = async ()=>{
  const data ={
    houseId:selectedRow.houseNameType,
    InFarmhouseTime:selectedRow.inTime,
    inNum:selectedRow.inHouseNum,
    pcId:props.pcId,
    preId:selectedRow.id,
    type:selectedRow.type

  }
  await PcApi.createInFarmhouse(data).then(res=>{
    // console.log(res,'res');    
    if(res){
      message.success('入舍成功')
      getList()
    }else{
      message.error('入舍失败')
    }

    reset()
  })


  moreOpen.value = false
  
}
// 取消操作
function cancel(){
  moreOpen.value =false
  reset()
}

// 入舍操作
const InHouseType=async (command:number)=>{
  const type = command
  await PcApi.houseListApi({type}).then(res=>{
    InHouseList.value =res
  })
  
}


// 蛋鸡淘汰
const openEliminationDialog = (row:any)=>{
  // console.log(row,'openEliminationDialog');
  eliminateOpen.value = true;
  title.value ='蛋鸡淘汰';
  Object.assign(outHouseForm,{
    ...row,
    id: row.id,
    houseName: row.houseName,
    expectedEliminateTime: row.expectedEliminateTime ,
    eliminateTime: row.eliminateTime,
    eliminateFinishTime: row.eliminateFinishTime,
    description: row.description
  })
}
// 蛋鸡取消
const Outcancel =()=>{
  eliminateOpen.value = false;
  reset()
}
// 蛋鸡淘汰确定
const eliminateSubmitForm =()=>{
  console.log('蛋鸡淘汰');
  const outData ={
    eliminateFinishTime: outHouseForm.eliminateFinishTime,
    eliminateTime: outHouseForm.eliminateTime,
    expectedEliminateTime: outHouseForm.expectedEliminateTime,
    id: outHouseForm.id,
    description: outHouseForm.description,
  }
  PcApi.eggOutApi(outData).then(res=>{
    console.log(res.code,'res');
    if(res){
      message.success('蛋鸡淘汰成功')
      eliminateOpen.value = false;
      getList()
    }else{
      message.error(res.msg)
    }
      
  })
}
// 表单重置
function reset(){
  Object.assign(selectedRow,{
    houseNameType:'',//入舍类型
    num:undefined,//未入舍数
    inHouseNum:undefined,//入舍数量
    inTime:undefined,//入舍日期
    description:'',//备注
    preId: undefined,
    type:undefined
  })
}


// const refreshTable = ()=>{
//   getList()
// }

onMounted(()=>{
})



</script>